package com.wanfu.exception;

import com.wanfu.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.dao.DataAccessException;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.jdbc.support.SQLExceptionTranslator;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public Result handleRuntimeException(RuntimeException e){
        // http请求异常
        if (e instanceof HttpMessageConversionException){
            log.error("【Bad Request】", e.getMessage(), e);
            return Result.error("Bad Request");
        }
        if (e instanceof AuthorizationException){
            log.error("【无操作权限Shiro】", e.getMessage(), e);
            return Result.error(Result.CODE_1403, "未授权：操作失败，请联系管理员授权");
        }
        if (e instanceof UnauthorizedException) {
            log.error("【无操作权限Shiro】", e.getMessage(), e);
            return Result.error(Result.CODE_1403, "UnauthorizedException。未授权：操作失败，请联系管理员授权");
        }
        if (e instanceof BusinessException){
            log.error("【业务异常】", e.getMessage(), e);
            return Result.error(e.getMessage());
        }
        if (e instanceof DataAccessException){
            log.error("【数据库异常：spring-dao】", e.getMessage(), e);
            return Result.error("DB异常：DataAccessException，请联系管理员");
        }
        if (e instanceof SQLExceptionTranslator){
            log.error("【数据库异常：sql异常】", e.getMessage(), e);
            return Result.error("DB异常：BadSqlGrammarException，请联系管理员");
        }

        log.error("【其他RuntimeException】", e.getMessage(), e);
        return Result.error();
    }


    /** 全局异常捕捉处理 */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result handleException(Exception e){
        if (e instanceof HttpRequestMethodNotSupportedException){
            return Result.error("不支持的请求方式/"+e.getMessage());
        }
        log.error("【未知异常】："+e.getMessage(),  e);
        return Result.error();
    }
}

